<?php

App::uses('AppRule', 'Lib');

class DaysAllowed extends AppRule {

    public $arguments = array(
        'days' => 'int',
        'per'  => array('month', 'year') 
    );
    
    public function apply(Leave $leave, $days=0, $per='year') {
        $ret  = true;
        $data = $leave->data['Leave'];
        
        $start = $data['start'];
        $end   = $data['end'];
        
        if ($days>0) {
            $time = strtotime($start);
            
            switch($per) {
                case 'month':
                    $fStart = date('Y-m-01', $time);
                    $m = date('m', $time);
                    $m = $m>11 ? 1 : $m+1;
                    $time2  = strtotime("Y-{$m}-1") - DAY;
                    $fEnd   = date('Y-m-d',  $time2);
                    break;
                    
                case 'year':
                    $fStart = date('Y-01-01', $time);
                    $fEnd   = date('Y-12-31', $time);
                    break;
            }
            
            $daysPassed = $leave->findUserLeaveDaysBetween($data['user_id'], $fStart, $fEnd);
            $daysToPass = $leave->daysBetween($start, $end);
            
            if (($daysPassed + $daysToPass) > $days) {
                $ret = false;
                $this->setError("Leave is limited to {$days} days/{$per} only.");
            }
        }
        
        return $ret;
    }

}

?>